#include "logwriter.h"

LogWriter::LogWriter(const QString&logPath,QObject*parent)
    :QThread(parent)
    ,m_logPath(logPath)
    ,m_running(false)

{
  this->m_queue=new BlockQueue(1000);
}


LogWriter::~LogWriter()
{
    m_running=false;
    m_queue->enqueue(LogMessage());
    // 2. 等待线程退出（最多等待3秒，避免无限阻塞）
    if (!wait(3000)) {
        qWarning() << "日志线程强制终止";
        terminate(); // 超时后强制终止
    }
}

void LogWriter::run()
{
    m_running=true;

    //尝试打开日志文件
    if(!checkAndCreateLogFile())
    {
        qWarning() << "无法打开日志文件，日志写入线程启动失败";
        return;
    }

    while(m_running)
    {
        LogMessage msg=m_queue->dequeue();

        if(msg.content.isEmpty())
        {
            continue;
        }

        // 检查是否需要切换日志文件（如按日期分割）
        if (!checkAndCreateLogFile()) {
            qWarning() << "日志文件切换失败，跳过当前日志";
            continue;
        }

        QString fromattedLog=formatLogMessage(msg);
        m_logStream<<fromattedLog<<Qt::endl;

        m_logStream.flush();

        emit logReadyForUI(fromattedLog);


    }
    processRemainingLogs();
    m_logFile.close();

}

bool LogWriter::checkAndCreateLogFile()
{
    QString dateStr=QDateTime::currentDateTime().toString("yyyy-MM-dd");
    QString fullPath=QString("%1/%2.log").arg(m_logPath).arg(dateStr);
    if(m_logFile.isOpen()&&m_logFile.fileName()==fullPath)
    {
        return true;
    }

    if(m_logFile.isOpen())
    {
        m_logFile.close();
    }


    QDir logDir(m_logPath);
    if(!logDir.exists()&&!logDir.mkpath("."))
    {
        qWarning() << "无法创建日志目录：" << m_logPath;
        return false;
    }

    //打开文件
    m_logFile.setFileName(fullPath);
    if (!m_logFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) {
        qWarning() << "无法打开日志文件：" << fullPath << "，错误：" << m_logFile.errorString();
        return false;
    }

    m_logStream.setDevice(&m_logFile);
    return true;
}

QString LogWriter::formatLogMessage(const LogMessage& msg)
{
    QDateTime time = msg.timestamp;
    QString timeStr = time.toString("yyyy-MM-dd HH:mm:ss.zzz");

    QString level;
    switch (msg.level) {
    case 0:
        level="Debug";
        break;
    case 1:
        level="Info";
        break;
    case 2:
        level="Warning";
        break;
    case 3:
        level="Error";
        break;
    case 4:
        level="Fatal";
        break;
    default:
        break;
    }

    return QString("[%1] [%2] [%3]")
        .arg(timeStr)
        .arg(level) // 级别占7个字符，对齐显示
        .arg(msg.content);

}


void LogWriter::processRemainingLogs()
{
    LogMessage msg;
    int count=0;
    m_queue->enqueue(msg);
    while(!msg.content.isEmpty())
    {
        if(!checkAndCreateLogFile())
        {
            m_logStream<<formatLogMessage(msg)<<Qt::endl;
            count++;
        }
    }
    if(count>0)
    {
        m_logStream.flush();
    }
}


void LogWriter::writeQueue(const LogMessage& msg)
{
    // 避免向已停止的线程写入日志
    if (m_running) {
        m_queue->enqueue(msg);
    }
}
